package com.inputabc.ct.v1.service.impl;

import com.inputabc.ct.v1.context.ContextParams;
import com.inputabc.ct.v1.handler.ForcedTranslationHandler;
import com.inputabc.ct.v1.handler.OfflineTranslationHandler;
import com.inputabc.ct.v1.handler.impl.ForcedTranslationHandlerImpl;
import com.inputabc.ct.v1.handler.impl.OfflineTranslationHandlerImpl;
import com.inputabc.ct.v1.service.TranslationService;
import com.inputabc.ct.v1.setting.KeySetting;
import com.inputabc.ct.v1.setting.SettingContext;
import com.inputabc.ct.v1.setting.TranslateSetting;
import com.inputabc.ct.v1.util.BaiduUtils;
import com.inputabc.ct.v1.util.DeepSeekUtils;
import com.inputabc.ct.v1.util.GoogleUtils;
import com.inputabc.ct.v1.util.QianfanUtils;
import com.inputabc.ct.v1.util.YoudaoUtils;
import org.apache.lucene.store.FSDirectory;

import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class TranslationServiceImpl implements TranslationService {
    private Map<Object, Object> contextParam = ContextParams.contextParam;
    private ForcedTranslationHandler fth = new ForcedTranslationHandlerImpl();
    private OfflineTranslationHandler oth = new OfflineTranslationHandlerImpl();
    private TranslateSetting translateSetting = SettingContext.translateSetting;
    private KeySetting keySetting = SettingContext.keySetting;
    
    // 本地翻译缓存，避免频繁访问Lucene索引
    private static final Map<String, String> localTranslationCache = new ConcurrentHashMap<>(200);
    
    // 五分钟清理一次本地缓存，防止内存占用过大
    private static final long LOCAL_CACHE_CLEANUP_INTERVAL = 5 * 60 * 1000; // 5分钟
    private long lastCleanupTime = System.currentTimeMillis();

    @Override
    public String translate(String content) throws Exception {
        // 检查和清理本地缓存
        checkAndCleanLocalCache();
        
        // 如果输入为空，直接返回空字符串
        if (content == null || content.trim().isEmpty()) {
            return "";
        }
        
        // 如果内容太长，截断处理
        if (content.length() > 5000) {
            content = content.substring(0, 5000);
            System.out.println("警告：翻译内容过长，已截断至5000字符");
        }
        
        // 首先检查本地缓存
        String cacheKey = content.trim();
        if (localTranslationCache.containsKey(cacheKey)) {
            return localTranslationCache.get(cacheKey);
        }

        // 格式化被翻译的内容
        content = fth.formatContent(content);
        String translated = null;

        FSDirectory fsdir = null;
        try {
            // 优先使用离线翻译
            fsdir = FSDirectory.open((Path) contextParam.get("indexPath"));
            translated = oth.getTranslatedContentFromIndex(content, fsdir);
            
            if (translated != null) {
                // 将离线翻译的结果缓存并返回
                localTranslationCache.put(cacheKey, translated);
                return translated;
            }
            
            // 进行在线翻译
            String translationEngine = translateSetting.getEngine();
            CompletableFuture<String> translationFuture = null;
            
            // 准备好文本，统一处理换行符等
            String cleanContent = content.replace("\r\n", " ").replace("\n", " ").replace("\t", " ").replaceAll("\\s{2,}", " ");
            
            try {
                if ("deepseek".equals(translationEngine)) {
                    // 使用异步翻译提高速度
                    String deepseekApiKey = keySetting.getDeepseek().getApiKey();
                    // 确保DeepSeekUtils中的API密钥是最新的
                    DeepSeekUtils.API_KEY = deepseekApiKey;
                    
                    translationFuture = DeepSeekUtils.translateAsync(cleanContent, 
                            translateSetting.getSource(), translateSetting.getTarget());
                } else if ("youdao".equals(translationEngine)) {
                    String youdaoAppKey = keySetting.getYoudao().getAppKey();
                    String youdaoAppSecret = keySetting.getYoudao().getAppSecret();
                    
                    // 有道翻译同步处理
                    translated = YoudaoUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget(), youdaoAppKey, youdaoAppSecret);
                } else if ("baidu".equals(translationEngine)) {
                    String baiduAppId = keySetting.getBaidu().getAppId();
                    String baiduSecurityKey = keySetting.getBaidu().getSecurityKey();
                    
                    // 百度翻译同步处理
                    translated = BaiduUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget(), baiduAppId, baiduSecurityKey);
                } else if ("google".equals(translationEngine)) {
                    // Google翻译同步处理
                    translated = GoogleUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget());
                } else if ("qianfan".equals(translationEngine)) {
                    // 千帆翻译同步处理
                    String qianfanApiKey = keySetting.getQianfan().getApiKey();
                    String qianfanSecretKey = keySetting.getQianfan().getSecretKey();
                    // 确保QianfanUtils中的API密钥是最新的
                    QianfanUtils.API_KEY = qianfanApiKey;
                    QianfanUtils.SECRET_KEY = qianfanSecretKey;
                    
                    translated = QianfanUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget());
                }
                
                // 如果使用了异步翻译，等待结果
                if (translationFuture != null) {
                    // 设置超时时间，防止长时间卡住
                    try {
                        translated = translationFuture.get(15, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        // 异步翻译超时或失败
                        e.printStackTrace();
                        throw new RuntimeException("翻译服务响应超时，请稍后再试");
                    }
                }
                
                // 将翻译后的内容写入索引库和本地缓存
                if (translated != null) {
                    // 过滤掉有可能的错误提示前缀（有些API在错误时会在结果前加前缀）
                    if (translated.startsWith("（") && translated.contains("）")) {
                        int index = translated.indexOf("）") + 1;
                        // 如果错误信息后面还有内容，保留这些内容
                        if (index < translated.length()) {
                            translated = translated.substring(index);
                        }
                    }
                    
                    oth.writeTranslatedContentToIndex(content, translated, fsdir);
                    localTranslationCache.put(cacheKey, translated);
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (e.toString().contains("java.net.")) {
                    throw new RuntimeException("无法连接到在线翻译引擎，请检查网络连接");
                } else if (e.toString().contains("timed out") || e.toString().contains("timeout")) {
                    throw new RuntimeException("翻译服务响应超时，请稍后再试");
                } else if (e.toString().contains("API密钥")) {
                    if ("deepseek".equals(translationEngine)) {
                        throw new RuntimeException("DeepSeek API密钥未设置或无效，请在设置中配置有效的API密钥");
                    } else if ("baidu".equals(translationEngine)) {
                        throw new RuntimeException("百度翻译API密钥未设置或无效，请在设置中配置有效的APP ID和密钥");
                    } else if ("youdao".equals(translationEngine)) {
                        throw new RuntimeException("有道翻译API密钥未设置或无效，请在设置中配置有效的应用ID和密钥");
                    } else if ("qianfan".equals(translationEngine)) {
                        throw new RuntimeException("百度千帆API密钥未设置或无效，请在设置中配置有效的API Key和Secret Key");
                    } else {
                        throw new RuntimeException("翻译API密钥未设置或无效，请在设置中配置");
                    }
                }
                throw e;
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.toString().contains("org.apache.lucene.index.IndexNotFoundException")) {
                // Lucene索引不存在，直接进行在线翻译
                String cleanContent = content.replace("\r\n", " ").replace("\n", " ").replace("\t", " ").replaceAll("\\s{2,}", " ");
                
                // 在catch块中重新获取翻译引擎类型
                String translationEngine = translateSetting.getEngine();
                
                if ("deepseek".equals(translationEngine)) {
                    // 使用DeepSeek翻译，但不使用异步方式，因为这是错误恢复路径
                    String deepseekApiKey = keySetting.getDeepseek().getApiKey();
                    // 确保DeepSeekUtils中的API密钥是最新的
                    DeepSeekUtils.API_KEY = deepseekApiKey;
                    
                    translated = DeepSeekUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget());
                } else if ("youdao".equals(translationEngine)) {
                    String youdaoAppKey = keySetting.getYoudao().getAppKey();
                    String youdaoAppSecret = keySetting.getYoudao().getAppSecret();
                    translated = YoudaoUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget(), youdaoAppKey, youdaoAppSecret);
                } else if ("baidu".equals(translationEngine)) {
                    String baiduAppId = keySetting.getBaidu().getAppId();
                    String baiduSecurityKey = keySetting.getBaidu().getSecurityKey();
                    translated = BaiduUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget(), baiduAppId, baiduSecurityKey);
                } else if ("google".equals(translationEngine)) {
                    translated = GoogleUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget());
                } else if ("qianfan".equals(translationEngine)) {
                    String qianfanApiKey = keySetting.getQianfan().getApiKey();
                    String qianfanSecretKey = keySetting.getQianfan().getSecretKey();
                    // 确保QianfanUtils中的API密钥是最新的
                    QianfanUtils.API_KEY = qianfanApiKey;
                    QianfanUtils.SECRET_KEY = qianfanSecretKey;
                    
                    translated = QianfanUtils.translate(cleanContent, translateSetting.getSource(),
                            translateSetting.getTarget());
                }
                
                // 将结果保存到本地缓存
                if (translated != null) {
                    localTranslationCache.put(cacheKey, translated);
                }
            } else {
                throw e;
            }
        }
        return translated;
    }
    
    /**
     * 检查并清理本地缓存
     */
    private void checkAndCleanLocalCache() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastCleanupTime > LOCAL_CACHE_CLEANUP_INTERVAL) {
            // 如果缓存条目超过150，清理到100条
            if (localTranslationCache.size() > 150) {
                // 采用简单的LRU策略：保留最近100个缓存项
                int toRemove = localTranslationCache.size() - 100;
                if (toRemove > 0) {
                    // 找出最旧的条目
                    localTranslationCache.entrySet().stream()
                        .sorted(Map.Entry.comparingByValue())
                        .limit(toRemove)
                        .map(Map.Entry::getKey)
                        .collect(Collectors.toList())
                        .forEach(localTranslationCache::remove);
                    
                    System.out.println("缓存清理完成，移除了 " + toRemove + " 个条目，当前缓存大小: " + localTranslationCache.size());
                }
            }
            lastCleanupTime = currentTime;
            
            // 同时清理DeepSeek的过期缓存
            DeepSeekUtils.cleanExpiredCache();
        }
    }
    
    /**
     * 清理所有缓存
     */
    public void clearAllCaches() {
        localTranslationCache.clear();
        DeepSeekUtils.clearCache();
    }
}
